<template >
  <div class="main_photo_item">
    <div>
      <div class="imgDivContent">
        <div v-for="(item, index) in img1" :key="index">
          <van-icon name="close" @click="delImg(item)" />
          <img :src="item.src" />
        </div>
      </div>
    </div>

    <div class="upload">
      <div @click="showActive('img1')" class="main_photo_item_content">
        <div class="img-list">
          <img class="uploadFile" :src="uploadFile" alt="" />
        </div>
      </div>
      <div class="upload-File">
        <van-uploader accept="file" :after-read="afterReads">
          <img class="uploadFile" :src="annex" alt="" />
        </van-uploader>
      </div>
    </div>
    <van-dialog v-model="showPup" :showCacelButton="false">
      <div class="infoScroll">
        <p class="defaults">
          <van-uploader :after-read="getphone" :max-size="4 * 1024 * 1024" capture="camera"> 拍照 </van-uploader>
        </p>
        <p class="defaults" >
          <van-uploader accept="file" :after-read="getphone"> 选择照片 </van-uploader>
        </p>
      </div>
    </van-dialog>
    <div class="center" v-if="wpslog.length > 0">
      <div style="display: flex; margin-top: 10px" v-for="(item, index) in wpslog" :key="index">
        <div>
          <div class="download">
            <div style="margin-right: 10px">
              <img class="download_img" :src="inject" alt="" />
            </div>
            <div>
              <div class="download_names">{{ item.originalName }}</div>
            </div>
            <!-- <div class="download_xia"> -->
            <van-icon name="close" @click="delWpsLog(item, index)" />
            <!-- </div> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { addUpload } from '@/api/api'
export default {
  data() {
    return {
      img1: [], //上传成功文件存储
      images: [], //文件id存储
      showPup: false,
      uploadFile: require('@/assets/img/btn_tupian.png'),
      annex: require('@/assets/img/btn_fujian.png'),
      inject: require('@/assets/img/wenjian.png'),
      appNo: '',
      actId: '',
      acDname: '', //服务器文件名
      acUrl: '', //服务器文件路径
      actType: '',
      fileList: [],
      action: [
        {
          name: '拍照',
          value: '1',
        },
        {
          name: '选择图片',
          value: '2',
        },
        {
          name: '取消',
          value: '0',
        },
      ],
      defsUrl: '',
      wpslog: [],
    }
  },
  created() {
    this.initData()
  },
  mounted() {},
  methods: {
    // 删除附件
    delWpsLog(val, index) {
      this.wpslog.splice(index, 1)
      this.images.some((item, i) => {
        if (item.id == val.id) {
          this.images.splice(i, 1)
          return true
        }
      })
      this.$emit('resultUoloadId', this.images)
    },
    // 上传附件
    afterReads(file) {
      let formData = new FormData()
      formData.append('fileCategory', 'annex')
      formData.append('mf', file.file)
      addUpload(formData).then((res) => {
        if (res.code === 200) {
          this.wpslog.push(res.result)
          let filePath = {
            src: `${res.result.downloadUrl}`,
            id: res.result.id,
            type: 'annex',
          }
          // this.img1.push(filePath)
          this.images.push(filePath)
          this.$emit('resultUoloadId', this.images)
        } else {
          this.$toast(res.message || '上传失败')
        }
      })
    },
    // 上传图片
    getphone(file) {
      let formData = new FormData()
      formData.append('fileCategory', 'img')
      formData.append('mf', file.file)
      // 图片上传
      addUpload(formData).then((res) => {
        if (res.code === 200) {
          let filePath = {
            src: `${res.result.downloadUrl}`,
            id: res.result.id,
            type: 'img',
          }
          this.img1.push(filePath)
          this.images.push(filePath)
          this.$emit('resultUoloadId', this.images)
          this.showPup = false
        } else {
          this.$toast(res.message || '上传失败')
          this.showPup = false
        }
      })
    },
    initData() {},
    base64ToBlob(base64Data) {
      let arr = base64Data.split(','),
        fileType = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        l = bstr.length,
        u8Arr = new Uint8Array(l)

      while (l--) {
        u8Arr[l] = bstr.charCodeAt(l)
      }
      return new Blob([u8Arr], {
        type: fileType,
      })
    },
    blobToFile(newBlob, fileName) {
      newBlob.lastModified = new Date().getTime()
      newBlob.lastModifiedDate = new Date()
      newBlob.name = fileName
      return newBlob
    },
    handleImgClick() {
      this.showBigImage = true
    },
    onChange(index) {
      this.showBigImageIndex = index
    },
    // 删除图片
    delImg(val) {
      this.img1.some((item, i) => {
        if (item == val) {
          this.img1.splice(i, 1)
          return true
        }
      })
      this.images.some((item, i) => {
        if (item.id == val.id) {
          this.images.splice(i, 1)
          return true
        }
      })
      this.$emit('resultUoloadId', this.images)
    },

    // 显示拍照选项
    showActive(val) {
      // console.log('asdsa')
      this.showPup = true
    },
    //拍照选择
    onSelect(item, index) {
      let _this = this
      if (item.value === '1') {
        _this.TakePictureType(item.value)
      }
      if (item.value === '2') {
        // _this.SelectPicrue(item.value)
      }
      if (item.value === '0') {
        _this.showPup = false
      }
      console.log(item, index)
    },
    // 拍照
    TakePictureType(mySourceType) {
      let _this = this
      _this.showPup = false
      // 调用拍照
      navigator.camera.getPicture(onSuccess, onFail, {
        quality: 50,
        targetWidth: 1024,
        destinationType: Camera.DestinationType.FILE_URI,
        encodingType: Camera.EncodingType.JPG,
        sourceType: mySourceType,
      })

      //拍照成功回调
      function onSuccess(imageURL) {
        _this.saveFile(imageURL)
      }

      function onFail(message) {
        //拍照失败回调
      }
    },
    //选择本地图片
    SelectPicrue() {
      let _this = this
      _this.showPup = false
      navigator.camera.getPicture(onSuccess, onFail, {
        quality: 50,
        targetWidth: 1024,
        destinationType: Camera.DestinationType.FILE_URI,
        encodingType: Camera.EncodingType.JPEG,
        sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
      })

      function onSuccess(imageURL) {
        //拍照回调
        _this.saveFile(imageURL)
      }

      function onFail(message) {
        //拍照回调
      }
    },
    // 拍照成功调用接口
    saveFile(imageURL) {
      console.log('imageURL', imageURL)
      let self = this
      window.resolveLocalFileSystemURL(
        imageURL,
        (fileEntry) => {
          new Promise((resolve, reject) => fileEntry.file(resolve, reject)).then((file) => {
            console.log('Drag a file one', file)
            self.uploadPost(file)
          })
        },
        () => {
          self.createNewFileEntry(imageURL)
        }
      )
    },
    createNewFileEntry(imageURL) {
      console.log(imageURL)
      let self = this
      window.resolveLocalFileSystemURL(cordova.file.cacheDirectory, function success(dirEntry) {
        // JPG file
        dirEntry.getFile('tempFile.jpeg', { create: true, exclusive: false }, function (fileEntry) {
          new Promise((resolve, reject) => fileEntry.file(resolve, reject)).then((file) => {
            console.log('Drag a file two', file)
            self.uploadPost(file)
          })
          console.log('got file: ' + fileEntry.fullPath)
        })
      })
    },
    uploadPost(file) {
      const fd = new FormData()
      const reader = new FileReader()
      reader.onloadend = async (e) => {
        const the_file = new Blob([e.target.result], { type: file.type })
        fd.append('fileCategory', 'img')
        fd.append('mf', the_file, file.name)
        console.log('mf', fd)
        addUpload(fd).then((res) => {
          if (res.code === 200) {
            let filePath = {
              src: `${res.result.downloadUrl}`,
              id: res.result.id,
              type: 'img',
            }
            console.log(filePath)
            this.img1.push(filePath)
            this.images.push(filePath)
            this.$emit('resultUoloadId', this.images)
          } else {
            this.$toast(res.message || '上传失败')
          }
        })
      }
      reader.readAsArrayBuffer(file)
    },
    afterRead(file) {
      let formData = new FormData()
      formData.append('fileCategory', 'annex')
      formData.append('mf', file.file)
      // 图片上传
      addUpload(formData).then((res) => {
        if (res.code === 200) {
          let filePath = {
            src: `${res.result.downloadUrl}`,
            id: res.result.id,
            type: 'annex',
          }
          this.img1.push(filePath)
          this.images.push(filePath)
          this.$emit('resultUoloadId', this.images)
        } else {
          this.$toast(res.message || '上传失败')
        }
      })
    },
  },
}
</script>

<style lang='less' scoped>
.main_photo_item {
  width: 30px;
  box-sizing: border-box;
}

.main_photo_item_content {
  width: 60px;
  height: 60px;
}

.main_photo_item_content img {
  width: 30px;
  height: 30px;
}

.upload-File {
  margin-left: 10px;
  width: 30px;
  height: 30px;
}

.upload-File img {
  width: 30px;
  height: 30px;
}

.imgDivContent {
  display: -webkit-box;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  width: 90vw;

  img {
    margin-left: 5px;
    width: 50px;
    height: 50px;
  }
}

.upload {
  display: flex;
  margin-top: 20px;
}
.center {
  background: #fff;
  width: 95%;
  margin: 10px auto;
  border-radius: 6px;
  // padding: 10px;
}

.download {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-top: 6px;
}

.download_img {
  width: 25px;
  height: 25px;
  margin: 8px 5px;
}

.download_name {
  color: #323232;
  font-size: 15px;
  width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-top: 2px;
}
.download_names {
  color: #323232;
  font-size: 14px;
  width: 240px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-top: 2px;
}
.infoScroll {
  margin: 0 auto;
  width: 65%;
  margin-top: 20px;

}
.defaults {
  width: 100%;
  text-align: center;
  border-bottom: 1px solid #ebebeb;
  padding-bottom: 10px;
  color: #666;
}
</style>
